package org.example.rmi;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.core.annotation.Order;
import org.springframework.remoting.rmi.RmiProxyFactoryBean;

import java.rmi.RemoteException;

@Configuration
@Order(99)
public class RmiClient {

    @Bean
    @DependsOn("rmiServiceExporter")
    public RmiProxyFactoryBean rmiProxyFactoryBean() {
        RmiProxyFactoryBean rmiProxyFactoryBean = new RmiProxyFactoryBean();
        rmiProxyFactoryBean.setServiceUrl("rmi://localhost:8848/hello");
        rmiProxyFactoryBean.setServiceInterface(Hello.class);
        rmiProxyFactoryBean.setRegistryClientSocketFactory(new MyRMIClientSocketFactory());
        rmiProxyFactoryBean.setRefreshStubOnConnectFailure(true);
        return rmiProxyFactoryBean;
    }

    @Bean
    @DependsOn("rmiServiceExporter2")
    public RmiProxyFactoryBean rmiProxyFactoryBean2() {
        RmiProxyFactoryBean rmiProxyFactoryBean = new RmiProxyFactoryBean();
        rmiProxyFactoryBean.setServiceUrl("rmi://localhost:8848/hello2");
        rmiProxyFactoryBean.setServiceInterface(Hello.class);
        rmiProxyFactoryBean.setRegistryClientSocketFactory(new MyRMIClientSocketFactory());
        rmiProxyFactoryBean.setRefreshStubOnConnectFailure(true);
        return rmiProxyFactoryBean;
    }

    public static void main(String[] args) throws RemoteException {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(RmiClient.class);
        Hello bean = (Hello) context.getBean("rmiProxyFactoryBean");
        bean.sayHello();
        Hello bean2 = (Hello) context.getBean("rmiProxyFactoryBean2");
        bean2.sayHello();
    }
}
